package com.ap.core.validation.message.rules;

import org.joda.time.LocalDateTime;

import com.ap.core.common.types.InputMessageType;
import com.ap.core.common.types.MessageStatus;
import com.ap.core.cxf.jaxb.managepayment.RetrieveRTPMessageType;
import com.ap.core.dao.BasketReferenceDao;
import com.ap.core.dao.MessageTimeOutDao;
import com.ap.core.dao.OrderPaymentDao;
import com.ap.core.domain.MessageTimeOut;
import com.ap.core.message.managepayment.info.RetrieveRTPMessageInfo;
import com.ap.core.validation.message.info.MessageValidationInfo;
import com.ap.core.validation.message.info.RTPOriginalInfo;
import com.ap.core.validation.rules.AbstractValidationRule;

/**
 * User: Dilip.Sridhar
 * Check for the Retrieval Expiry Timestamp of the record relating to the AP Transaction ID should be checked 
 * to ensure the RTP that it is stored on AP Core is within a valid expiry time.
 */
public class TV0001Rule extends AbstractValidationRule<MessageValidationInfo<RetrieveRTPMessageInfo, RTPOriginalInfo>> {
	
	private OrderPaymentDao orderPaymentDao;
	private BasketReferenceDao basketReferenceDao;
	private MessageTimeOutDao messageTimeOutMasterDao;

    @Override
    public boolean validate(MessageValidationInfo<RetrieveRTPMessageInfo, RTPOriginalInfo> infoObject) {
    	boolean pass =true; 
    	LocalDateTime currentDateTime = new LocalDateTime();
        if(currentDateTime.isAfter(infoObject.getOriginalInfo().getRetrievalExpiryTime()) 
        		&& currentDateTime.isBefore(infoObject.getOriginalInfo().getReconCutoffEndTime())){
        	pass = false;
        }
        return pass;
    }
    
    @Override
    public void onFailureAction(MessageValidationInfo<RetrieveRTPMessageInfo, RTPOriginalInfo> infoObject) {    	
    	 MessageTimeOut messageTimeOut = messageTimeOutMasterDao.findById(RetrieveRTPMessageType.RETRIEVERTP.name());
         LocalDateTime confirmationExpiryTime = new LocalDateTime().plusSeconds(messageTimeOut.getTimeOutSeconds());
    	 orderPaymentDao.updateOrderPayment(infoObject.getOriginalInfo().getOriginalAPTxnId(), MessageStatus.LATE_RETRIEVAL, confirmationExpiryTime);
         if(InputMessageType.SUBMITRTPFORBRN.equals(infoObject.getOriginalInfo().getOriginalInputMessageType())){
            basketReferenceDao.updateBRNRetrieved(infoObject.getOriginalInfo().getOriginalAPTxnId());
         }
    }
    
    public void setOrderPaymentDao(OrderPaymentDao orderPaymentDao) {
        this.orderPaymentDao = orderPaymentDao;
    }

    public void setBasketReferenceDao(BasketReferenceDao basketReferenceDao) {
        this.basketReferenceDao = basketReferenceDao;
    }

	public void setMessageTimeOutMasterDao(MessageTimeOutDao messageTimeOutMasterDao) {
		this.messageTimeOutMasterDao = messageTimeOutMasterDao;
	}
    
    

}
